import os
from threading import Thread

import cv2
import sys

from models.user import User

images_list = []
need_save = True
user = User()

def save_image():
    global images_list
    while need_save or len(images_list) > 0:
        if len(images_list) > 0:
            image = images_list.pop(0)
            cv2.imwrite(image["img_name"], image["image"])
            print(image["img_name"])


def CatchPICFromVideo(window_name, camera_idx, catch_pic_num, path_name):
    global images_list, need_save
    cv2.namedWindow(window_name)
    try:
        os.mkdir(path_name)
    except Exception as e:
        pass
    
    # 视频来源，可以来自一段已存好的视频，也可以直接来自USB摄像头
    cap = cv2.VideoCapture(camera_idx)
    
    # 告诉OpenCV使用人脸识别分类器
    classfier = cv2.CascadeClassifier(r'./haarcascade_frontalface_alt2.xml')
    
    # 识别出人脸后要画的边框的颜色，RGB格式
    color = (128, 128, 128)
    
    num = 0
    while cap.isOpened():
        ok, frame = cap.read()  # 读取一帧数据
        if not ok:
            break
        
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 将当前桢图像转换成灰度图像
        
        # 人脸检测，1.2和2分别为图片缩放比例和需要检测的有效点数
        faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
        if len(faceRects) > 0:  # 大于0则检测到人脸
            for faceRect in faceRects:  # 单独框出每一张人脸
                x, y, w, h = faceRect
                
                # 将当前帧保存为图片
                img_name = '%s/%d.jpg' % (path_name, num)
                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                images_list.append(
                    {
                        "img_name": img_name,
                        "image": image,
                    }
                )
                
                num += 1
                if num > (catch_pic_num):  # 如果超过指定最大保存数量退出循环
                    break
                
                # 画出矩形框
                cv2.rectangle(frame, (x - 12, y - 12), (x + w + 12, y + h + 12), color, 2)
                
                # 显示当前捕捉到了多少人脸图片了，这样站在那里被拍摄时心里有个数，不用两眼一抹黑傻等着
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(frame, 'Over:%d %%' % (num), (x - 15, y - 15), font, 1, (255, 0, 255), 4)
                
                # 超过指定最大保存数量结束程序
        if num > (catch_pic_num): break
        
        # 显示图像
        cv2.imshow(window_name, frame)
        c = cv2.waitKey(10)
        if c & 0xFF == ord('q'):
            break
            
            # 释放摄像头并销毁所有窗口
    cap.release()
    need_save = False
    cv2.destroyAllWindows()


def storage_user(name):
    source_dict = {}
    for i in range(50):
        try:
            img2gray = cv2.imread("./data/{}/{}.jpg".format(name, i),0)
            source = cv2.Laplacian(img2gray, cv2.CV_64F).var()
            source_dict[source] = "./data/{}/{}.jpg".format(name, i)
        except Exception as e:
            continue
    
    source_list = sorted(source_dict.items(),key=lambda x:x[0],reverse=True)
    print(source_list[0])
    with open(source_list[0][1],"rb+") as rf:
        with open("./storage/{}.jpg".format(name),"wb+") as wf:
            content = rf.read()
            wf.write(content)
    user.user_create(username=name,image_path="./storage/{}.jpg".format(name),viewname=name)


if __name__ == '__main__':
    if len(sys.argv) != 1:
        print("Usage:%s camera_id face_num_max path_name\r\n" % (sys.argv[0]))
    else:
        while True:
            name = input("输入录入者姓名:\n")
            if name == "exit":
                break
            save_th = Thread(target=save_image)
            crame_th = Thread(target=CatchPICFromVideo, args=("截取人脸", 0, 50, './data/{}'.format(name)))
            crame_th.start()
            save_th.start()

            crame_th.join()
            save_th.join()

            storage_user(name)
